<?php
/**
 * 库存站点（基础）
 * (model)
 */

namespace App\Models\Basics;

use Illuminate\Database\Eloquent\Model;
class SysIArea extends Model
{
    protected $table = 'b_sys_i_area';

    public $timestamps = false;

    protected $guarded = [];

    public function area()
    {
        return $this->belongsTo(SysArea::class,'area_id');
    }

    public function country(){
        return $this->hasManyThrough(
            SysCountry::class,
            SysICountry::class,
            'area_id',//中间表 ->对应到LocalKey
            'id',//目标表
            'area_id',//当前模型
            'country_id'//中间表   ->对应到目标表 SecondKey
        );
    }

    public static function options()
    {
        $re = self::query()->get()->map(function ($model){
            return collect(['area_id' => $model->area_id,
                'area' => $model->area->area ?? '']);
        });
        return $re->pluck('area','area_id');
    }

    protected static function boot()
    {
        parent::boot();

        static::deleting(function ($model){
            $count = SysICountry::query()->where('country_id',$model->id)->count();
            if($count > 0){
                throw new \Exception('使用中勿删除');
            }
        });
    }

}
